//
//  TRMyCollectViewController.m
//  WeiMiLan
//
//  Created by cong on 14-8-1.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRMyCollectViewController.h"
#import "PullCollectionView.h"
#import "TRMemuCell.h"
#import "TRUploadEditerViewController.h"

@interface TRMyCollectViewController ()<PullCollectionViewDelegate,CHTCollectionViewDelegateWaterfallLayout>
@property (strong, nonatomic) IBOutlet PullCollectionView *collectionView;
@property (strong, nonatomic) PullCollectionView *xxx;
@property(nonatomic,assign)int  pageNum;
@property(nonatomic,assign)NSInteger oldNum;
@property(nonatomic,strong)NSMutableArray * chongfuIDs;
@property(nonatomic,strong)NSMutableArray * famousArray;
@property(nonatomic,strong)NSArray *mySends;

@end

@implementation TRMyCollectViewController

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSArray * goods = self.famousArray;
    TRMemuCell *cell =[[TRMemuCell alloc] init];
    cell.info = [goods objectAtIndex:indexPath.row];
    return [cell getSize];
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 2;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 2;
}



- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    if (self.goodsStype==TRMyCollect) {
        self.weChatNavigationBar.titleLabel.text=@"我的收藏";
    }
    if (self.goodsStype==TRMySend) {
        self.weChatNavigationBar.titleLabel.text=@"我的上传";
    }
    
    
    [self.weChatNavigationBar .leftButton addTarget:self action:@selector(exit)  forControlEvents:UIControlEventTouchUpInside];
    [self.weChatNavigationBar.rightButton setHidden:YES];
    
}

-(void)exit
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//    
    CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
//    layout.headerHeight = 0;
//    layout.footerHeight = 0;
//    layout.minimumColumnSpacing = 10;
//    layout.minimumInteritemSpacing = 10;
    layout.columnCount = 1;
    CGRect r = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
    self.collectionView=[[PullCollectionView alloc] initWithFrame:r collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource=self;
    self.collectionView.alwaysBounceVertical = YES;
    [self.collectionView setCollectionViewLayout:layout];
    //  self.collectionView.collectionViewLayout = layout;
    self.famousArray = [@[]mutableCopy];
    self.chongfuIDs = [@[]mutableCopy];
    self.pageNum = 1;
    self.collectionView.pullBackgroundColor = [UIColor whiteColor];
    self.collectionView.pullTextColor = [UIColor blackColor];
    [self.collectionView registerNib:[UINib nibWithNibName:@"TRMemuCell" bundle:nil] forCellWithReuseIdentifier:@"TRMemuCell"];
  //  self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.clearsContextBeforeDrawing = YES;
    self.collectionView.backgroundColor = [UIColor whiteColor];
 //   [self.collectionView numberOfItemsInSection:1];
   [self.view addSubview:self.collectionView];
    [self initNavigation];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.goodsStype==TRMyCollect) {
        [self.famousArray removeAllObjects];
    }
    
    //加产品，加请求
    [self updataMyData:self.pageNum];
}
-(void)pullCollectionViewDidTriggerRefresh:(PullCollectionView *)pullCollectionView{
    [self updataMyData:self.pageNum];
}

-(void)reflushNow{
    [self.collectionView endRefreshing];
    [self.collectionView endLoadingMore];
}

- (void)pullCollectionViewDidTriggerLoadMore:(PullCollectionView*)pullCollectionView{
    [self updataMyData:(++self.pageNum)];
}

-(void)updataMyData:(int)num{
    if (num<=1) {
        [self.famousArray removeAllObjects];
    }

    
    NSDictionary *dic = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    
    if (dic.count == 0) {
        return;
    }
    
    [MBProgressHUD showMessage:@"加载中..."];
    
    NSString *uid = [dic ql_stringForKey:@"ID"];
    NSLog(@"%d",(int)self.goodsStype);
    NSDictionary * params;
    switch ((int)self.goodsStype) {
        case TRMyCollect:
            params = @{
                       USERID:uid,
                       TYPE:[NSString stringWithFormat:@"%d",DirectoryCollection],
                       PAGE_NUM:QLIntToNumber(num),
                       PRODUCT_TYPE_ORDER_FIELD:DIR_ORDER_FIELD_CREATEDATE,
                       PRODUCT_TYPE_ORDER_DIRECTION:DIR_ORDER_DIRECTION_ASC
                       };
            break;
            
        case TRMySend:
            
            params = @{TYPE: @"1016",
                       USERID: uid,
                       PAGE_NUM:QLIntToNumber(num),
                       PRODUCT_TYPE_ORDER_FIELD:DIR_ORDER_FIELD_CREATEDATE,
                       PRODUCT_TYPE_ORDER_DIRECTION:DIR_ORDER_DIRECTION_ASC
                       };
            
            break;
    }
    [ApplicationDelegate.webAPI getWebAPIWithParams:params andMethodNode:NODE_DIRECTORY completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
        //[MBProgressHUD showMessage:@"记载成功"];
        [MBProgressHUD hideHUD];
        NSString * message = responseObject[@"MESSAGE_INFO"][@"MESSAGE"];
        
        if (message.length>2) {
            //              MMProgressHUDShowWithStatus(message);
            [SVProgressHUD showImage:nil status:message];
        }
        if (state==1) {
            if ([responseObject[@"MESSAGE_INFO"][@"CODE"] isEqualToString:@"0000"]) {
                if (self.famousArray.count==0) {
                    //第一页
                    if ([responseObject[@"PACKAGE_RSP"][@"PACKAGE"] isKindOfClass:[NSDictionary class]]) {
                        [self.famousArray addObject:responseObject[@"PACKAGE_RSP"][@"PACKAGE"]];
                    }else{
                        self.famousArray = [NSMutableArray arrayWithArray:responseObject[@"PACKAGE_RSP"][@"PACKAGE"]];
                    }
                }else{
                    //后几页
                    //是多个字典
                    if ([responseObject[@"PACKAGE_RSP"][@"PACKAGE"] isKindOfClass:[NSDictionary class]]) {
                        if (![self.chongfuIDs containsObject:responseObject[@"PACKAGE_RSP"][@"PACKAGE"][@"ID"]]) {
                            [self.famousArray addObject:responseObject[@"PACKAGE_RSP"][@"PACKAGE"]];
                        }
                    }else{
                        
                        //单个对象
                        for (NSDictionary * famousDict in responseObject[@"PACKAGE_RSP"][@"PACKAGE"]) {
                            
                            if (![self.chongfuIDs containsObject:famousDict[@"ID"]]) {
                                [self.famousArray addObject:famousDict];
                            }
                            
                        }
                    }
                }
                
                for (NSDictionary * famousDict in self.famousArray) {
                    if (![self.chongfuIDs containsObject:famousDict[@"ID"]]) {
                        [self.chongfuIDs addObject:famousDict[@"ID"]];
                    }
                    
                }
                if ([responseObject[@"PAGE_INFO"][@"COUNT"] integerValue]>self.famousArray.count) {
                    self.collectionView.refreshFooterView.isend = NO;
                }else{
                    self.collectionView.refreshFooterView.isend = YES;
                }
                [self.collectionView endRefreshing];
                [self.collectionView endLoadingMore];
                [self.collectionView reloadData];
            }
        }else{
            [SVProgressHUD showErrorWithStatus:message];
        }
    }];
}



#pragma mark - collectview部分
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    self.oldNum =self.famousArray.count;
    
    return self.famousArray.count;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TRMemuCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"TRMemuCell" forIndexPath:indexPath];
    cell.backgroundColor=[UIColor whiteColor];
    [cell.imageViewIcon setImageWithURL:[NSURL URLWithString:self.famousArray[indexPath.row][@"THUMBNAIL_URL"]] placeholderImage:ApplicationDelegate.loadingImage];
  //  cell.selectImageView.hidden= YES;
    
    cell.label2.text=self.famousArray[indexPath.row][@"DESCRIPTION"];
    cell.label1.text=self.famousArray[indexPath.row][@"USER_NAME"];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *timeStr = self.famousArray[indexPath.row][@"CREATE_DATE"];
    NSDate *createDate = [formatter dateFromString:timeStr];
    
    
    NSString *str = [NSString stringWithFormat:@"%@",[createDate ql_ToString]];
    str = [str substringFromIndex:5];
    cell.timeLabel.text =str;
    
    NSString *comment = self.famousArray[indexPath.row][@"COMMENT_NUM"];
    NSInteger commentNum = [comment integerValue];
    cell.label3.text = [NSString stringWithFormat:@"评论 %zd",commentNum];
    
//    if (![NSString isBlankString:self.famousArray[indexPath.row][@"TYPE"]]) {
//        cell.kTYPELabel.text=self.famousArray[indexPath.row][@"TYPE"];
//    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.weChatNavigationBar.titleLabel.text isEqualToString:@"我的上传"]) {
        TRUploadEditerViewController *vc = [[TRUploadEditerViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        vc.productTypeId = self.famousArray[indexPath.row][@"ID"];
    }else{
        TRProductDetailViewController *vc = [[TRProductDetailViewController alloc] init];
        vc.productTypeId = self.famousArray[indexPath.row][@"ID"];
        [self presentViewController:vc animated:YES completion:nil];
    }
}

@end
